package com.lotter.api.service;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lotter.common.enumobject.RandomTypeEunm;
import com.lotter.common.enumobject.SiteMessageFormat;
import com.lotter.common.exception.LotterCusException;
import com.lotter.common.util.CaptchaUtil;
import com.lotter.common.util.DateUtil;
import com.lotter.common.util.SendSMSUtil;
import com.lotter.dao.MobileCodeMapper;
import com.lotter.model.code.MobileCode;

/**
 * 发送短信接口
 * @author zhangzechi
 *
 */
@Service
public class SmsService{
	

	// 记录日志 
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
    private MobileCodeMapper mobileCodeMapper ;
	
	/**
	 * 发送手机短信
	 * @param request
	 * @param mobile
	 * @return
	 */
    @Transactional(rollbackFor=Exception.class)
	public void sendSms( String mobile ,SiteMessageFormat siteMessageFormat){
		String code = CaptchaUtil.generateVerifyCode(6, RandomTypeEunm.NUMBER.getCode());
		logger.info(siteMessageFormat.getContent() +"本次的验证码是"+ code);
		String content = String.format(siteMessageFormat.getContent(), code);
		try {
			SendSMSUtil.send(mobile,content);
			MobileCode mobileCode = new MobileCode();
			mobileCode.setMobile(mobile);
			mobileCode.setCode(code);
			// 2分钟
			mobileCode.setTimeout(DateUtil.getDateplusDay(new Date(), null, null, 2, null));
			mobileCodeMapper.insert(mobileCode);
			siteMessageFormat= null;
		} catch (Exception e) {
		   logger.error("发送短信失败");
		   return ;
		} 
	}
	
	//获取验证码
	public String findMobileCode(String mobile) throws LotterCusException{
		return mobileCodeMapper.findCodeByMobile(mobile, new Date());
	}

	
	
	public static void main(String[] args) {
		SiteMessageFormat siteMessageFormat = SiteMessageFormat.REGISTER_NOTICE;
		String code = CaptchaUtil.generateVerifyCode(6, RandomTypeEunm.NUMBER.getCode());
		siteMessageFormat.setContentArgs(code);
		System.out.println(siteMessageFormat.getContent());
	}
}
